package com.hfjyz.payment.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class DBAccessor {
    private static final String SELECT_SQL = "select id, orderState from orderInfo where orderDate like '%s' and deleteFlg = 0";
    private static final String UPDATE_SQL = "update orderInfo set orderState=?, updateDate = ? where id=? and orderState !=? and deleteFlg = 0";

    public static Connection getConnection(String driver, String jdbcUrl, String user, String password)
            throws Exception {
        Class.forName(driver);
        Connection con = DriverManager.getConnection(jdbcUrl, user, password);
        return con;
    }

    public static List<String> getAllOrderNum(Connection conn, String orderDate) throws Exception {
        PreparedStatement pst = null;
        try {
            String sql = String.format(SELECT_SQL, orderDate + "%");
            pst = conn.prepareStatement(sql);
            ResultSet rt = pst.executeQuery();
            
            List<String> orderNumList = new ArrayList<String>();
            while (rt.next()) {
                orderNumList.add(rt.getString("id"));
            }

            return orderNumList;
        } finally {
            pst.close();
        }
    }

    public static void updateOrderState(Connection conn, int orderStat, String orderNum) throws Exception {
        PreparedStatement pst = null;
        try {
            pst = conn.prepareStatement(UPDATE_SQL);
            pst.setInt(1, orderStat);
            pst.setObject(2, new Date());
            pst.setString(3, orderNum);
            pst.setInt(4, orderStat);
            pst.executeUpdate();
        } finally {
            pst.close();
        }
    }
}
